﻿/********************************************************************************
    Copyright (C) Binod Nepal, Planet Earth Solutions Pvt. Ltd., Kathmandu.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Configuration;

namespace MixNP.Web.Classifieds
{
    public partial class CategoryView : MixNP.BusinessLayer.BaseClass
    {
        int parentCategoryId;
        int categoryId;
        string parentAlias;
        string alias;

        string queryLike;
        string queryPriceFrom;
        string queryPriceTo;
        string queryCity;
        string querySort;
        string queryPageNumber;

        protected void Page_Load(object sender, EventArgs e)
        {
            parentAlias = Pes.Utility.Conversion.TryCastString(this.Page.RouteData.Values["parent-alias"]);
            alias = Pes.Utility.Conversion.TryCastString(this.Page.RouteData.Values["alias"]);


            if (string.IsNullOrWhiteSpace(alias))
            {
                categoryId = int.MinValue;
            }
            else
            {
                categoryId = MixNP.BusinessLayer.Categories.GetCategoryId(alias);
            }

            parentCategoryId = MixNP.BusinessLayer.Categories.GetCategoryId(parentAlias);

            if (parentCategoryId.Equals(int.MinValue))
            {
                MixNP.BusinessLayer.Helpers.PageHelper.ContentNotFound(Context);
                return;
            }

            if (categoryId.Equals(int.MinValue))
            {
                HeadingLiteral.Text = MixNP.BusinessLayer.Categories.GetCategoryName(parentCategoryId);
            }
            else
            {
                HeadingLiteral.Text = MixNP.BusinessLayer.Categories.GetCategoryName(categoryId);
            }

            this.FillCategories();

            if (string.IsNullOrWhiteSpace(Pes.Utility.Conversion.TryCastString(Session["UserId"])))
            {
                AlertPanel.Visible = false;
            }

            if (!IsPostBack)
            {
                this.GetQueryData();
                this.Paginate();
            }

            this.Page.Title = HeadingLiteral.Text;
            this.Page.MetaKeywords = alias;
        }

        private void Paginate()
        {
            string strConn = ConfigurationManager.ConnectionStrings["PESConnectionString"].ConnectionString;
            System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(strConn);

            System.Data.SqlClient.SqlCommand Cmd = new System.Data.SqlClient.SqlCommand("dbo.GetPagedItems", cn);
            Cmd.CommandType = System.Data.CommandType.StoredProcedure;
            System.Data.SqlClient.SqlDataReader dr;

            decimal priceFrom = Pes.Utility.Conversion.TryCastDecimal(queryPriceFrom);
            decimal priceTo = Pes.Utility.Conversion.TryCastDecimal(queryPriceTo);
            short city = Pes.Utility.Conversion.TryCastShort(queryCity);
            short sort = Pes.Utility.Conversion.TryCastShort(querySort);
            int pageNumber = Pes.Utility.Conversion.TryCastShort(queryPageNumber);

            bool hasRows = false;

            if (priceFrom.Equals(decimal.MinValue)) { priceFrom = 0; }
            if (priceTo.Equals(decimal.MinValue)) { priceTo = 0; }
            if (city.Equals(short.MinValue)) { city = 0; }
            if (sort.Equals(short.MinValue)) { sort = 0; }
            if (pageNumber.Equals(int.MinValue)) { pageNumber = 0; }

            if (pageNumber.Equals(0)) { pageNumber = 1; }

            Cmd.Parameters.Add("@PageNumber", System.Data.SqlDbType.Int).Value = pageNumber;
            Cmd.Parameters.Add("@NameLike", System.Data.SqlDbType.NVarChar, 128).Value = queryLike;
            Cmd.Parameters.Add("@CategoryId", System.Data.SqlDbType.Int).Value = categoryId;
            Cmd.Parameters.Add("@PriceFrom", System.Data.SqlDbType.Money).Value = priceFrom;
            Cmd.Parameters.Add("@PriceTo", System.Data.SqlDbType.Money).Value = priceTo;
            Cmd.Parameters.Add("@CityId", System.Data.SqlDbType.SmallInt).Value = city;
            Cmd.Parameters.Add("@Order", System.Data.SqlDbType.SmallInt).Value = sort;

            Cmd.Parameters.Add("@ItemCount", System.Data.SqlDbType.Int).Direction = System.Data.ParameterDirection.Output;

            cn.Open();
            dr = Cmd.ExecuteReader();


            CardRepeater.DataSource = dr;
            CardRepeater.DataBind();
            hasRows = dr.HasRows;
            dr.Close();
            cn.Close();

            Int32 _totalRecords = Convert.ToInt32(Cmd.Parameters["@ItemCount"].Value);

            TopPager.RecordCount = _totalRecords;
            TopPager.PageSize = 20;

            BottomPager.RecordCount = _totalRecords;
            BottomPager.PageSize = 20;

            TopPager.ShowDisabledButtons = false;
            BottomPager.ShowDisabledButtons = false;
            if (_totalRecords.Equals(0) || !hasRows)
            {
                TopPager.Visible = false;
                BottomPager.Visible = false;
                NothingLiteral.Text = "<h2>Nothing found. :(</h2>";
            }
        }

        private void FillCategories()
        {
            string left = string.Empty, middle = string.Empty, right = string.Empty;
            string html = string.Empty;
            string url = string.Empty;

            html += "<ul>";

            using (System.Data.DataTable categories = MixNP.BusinessLayer.Categories.GetCategories(parentCategoryId))
            {
                foreach (System.Data.DataRow childRow in categories.Rows)
                {
                    url = ResolveUrl("~/view/" + parentAlias + "/" + childRow["alias"].ToString() + ".mix");

                    html += "<li>";
                    html += "<a href=\"{0}\" title=\"{1}\">{1} ({2})</a>";
                    html += "</li>";
                    html = string.Format(html, url, childRow["CategoryName"].ToString(), childRow["TotalItems"].ToString());

                }
            }

            html += "</ul>";

            CategoriesLiteral.Text = html;
        }

        private void GetQueryData()
        {
            queryLike = Pes.Utility.Conversion.TryCastString(this.Page.Request.QueryString["Name"]);
            queryPriceFrom = Pes.Utility.Conversion.TryCastString(this.Page.Request.QueryString["PriceFrom"]);
            queryPriceTo = Pes.Utility.Conversion.TryCastString(this.Page.Request.QueryString["PriceTo"]);
            queryCity = Pes.Utility.Conversion.TryCastString(this.Page.Request.QueryString["City"]);
            querySort = Pes.Utility.Conversion.TryCastString(this.Page.Request.QueryString["Sort"]);
            queryPageNumber = Pes.Utility.Conversion.TryCastString(this.Page.Request.QueryString["PageNumber"]);

            NameTextBox.Text = queryLike;
            PriceFromTextBox.Text = queryPriceFrom;
            PriceToTextBox.Text = queryPriceTo;

            if (!string.IsNullOrWhiteSpace(queryCity))
            {
                CityDropDownList1.SelectedValue = queryCity;
            }

            if (!string.IsNullOrWhiteSpace(querySort))
            {
                SortByDropDownList.SelectedValue = querySort;
            }
        }

        protected void FilterButton_Click(object sender, EventArgs e)
        {
            string like = NameTextBox.Text;
            decimal priceFrom = Pes.Utility.Conversion.TryCastDecimal(PriceFromTextBox.Text);
            decimal priceTo = Pes.Utility.Conversion.TryCastDecimal(PriceToTextBox.Text);
            string city = CityDropDownList1.SelectedValue;
            string sort = Pes.Utility.Conversion.TryCastShort(SortByDropDownList.SelectedValue).ToString();

            string cityQuery = string.Empty;
            string nameQuery = string.Empty;
            string priceFromQuery = string.Empty;
            string priceToQuery = string.Empty;
            string sortQuery = string.Empty;


            if (!string.IsNullOrWhiteSpace(city))
            {
                cityQuery = "&City=" + city;
            }

            if (!string.IsNullOrWhiteSpace(like))
            {
                nameQuery = "&Name=" + like;
            }

            if (!decimal.MinValue.Equals(priceFrom))
            {
                if (priceFrom > 0)
                {
                    if (priceTo > priceFrom)
                    {
                        priceFromQuery = "&PriceFrom=" + priceFrom.ToString().Replace(".0000", "");
                        priceToQuery = "&PriceTo=" + priceTo.ToString().Replace(".0000", "");
                    }
                }
            }

            sortQuery = "&Sort=" + sort;

            StringBuilder redirect = new StringBuilder();
            redirect.Append(Request.Url.AbsolutePath);
            redirect.Append("?Filter=1");
            redirect.Append(cityQuery);
            redirect.Append(nameQuery);
            redirect.Append(priceFromQuery);
            redirect.Append(priceToQuery);
            redirect.Append(sortQuery);

            Response.Redirect(redirect.ToString());
        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            string args = Request.Form["AlertRadio"];
            bool save = args.Equals("Yes");

            short cityId = Pes.Utility.Conversion.TryCastShort(AlertCityDropDownList.SelectedValue);
            decimal priceFrom = Pes.Utility.Conversion.TryCastDecimal(AlertPriceFromTextBox.Text);
            decimal priceTo = Pes.Utility.Conversion.TryCastDecimal(AlertPriceToTextBox.Text);

            if (save)
            {
                MixNP.BusinessLayer.Alerts.AlertMe.SaveAlert(User.Identity.Name, categoryId, cityId, priceFrom, priceTo);
            }
            else
            {
                MixNP.BusinessLayer.Alerts.AlertMe.DeleteAlert(User.Identity.Name, categoryId);
            }
        }

    }
}